//
//  SLDeployViewController.m
//  StarLight
//
//  Created by 吴涛 on 16/5/9.
//  Copyright © 2016年 Duke.Wu. All rights reserved.
//
#import "UMSocial.h"
#import "SLDeployViewController.h"
#import "SLAddBoatViewController.h"
#import "SLAddGoodsViewController.h"
#import "SLMineViewModel.h"
#import "SLDeployBoatsCollectionViewCell.h"
#import "SLDeployGoodsCollectionViewCell.h"
#import "SLSetBoatViewController.h"
#import "SLSetGoodsViewController.h"
#import "SLRefreshBoatViewController.h"
#import "STPopup.h"
#import "MJRefresh.h"
#import "SLRecomendViewController.h"
#import "SLShareManager.h"
#import "SLScrollerTextView.h"



@interface SLDeployViewController ()<UICollectionViewDelegate, UICollectionViewDataSource,SLDeployBoatsCollectionViewCellDelegate,SLDeployGoodsCollectionViewCellDelegate,UMSocialUIDelegate>

@property (nonatomic, strong) UIButton *historyBtn;

@property (nonatomic, strong) SLDeployViewModel * deployVM;

@property (nonatomic, strong) UICollectionView *depolyCollectionView;

@property (nonatomic, strong) SLMineViewModel *mineModel;

@property (nonatomic, assign) NSInteger userType;

@property (nonatomic, strong) UIButton *shareBtn;

@property (nonatomic, strong) SLScrollerTextView *scrollTextView;

@property (nonatomic, strong) UIImageView *warnImageView;



@end

@implementation SLDeployViewController

- (void)viewDidLoad {
    [super viewDidLoad];
  self.userType = self.mineModel.indexModel.type;
  
  if (self.userType == 1) {
    self.deployVM = [[SLDeployViewModel alloc] initWithType:DeployViewModelTypeGoodOwner];
  }else{
    self.deployVM = [[SLDeployViewModel alloc] initWithType:DeployViewModelTypeShipOwner];
  }
  
  
  [self addUI];
  [self addConstrains];
  [self addObservers];

}

- (void)viewWillAppear:(BOOL)animated{
  [super viewWillAppear:animated];
  self.view.backgroundColor = [UIColor defeutBackgroudColor];
//  [self.deployVM first];
  if (self.userType == 1) {
    [self.naviHeader setNaviTitleWithString:@"发布的货源"];
  }else{
    [self.naviHeader setNaviTitleWithString:@"24小时智能配货"];
      
//      [self.naviHeader setNaviRightTitleWithString:@"分享"];
  }
}

- (void)addUI{
  [self.naviHeader addSubview:self.historyBtn];
  [self.naviHeader addSubview:self.shareBtn];
  [self.view addSubview:self.depolyCollectionView];
}

- (void)setUpStauts{
  
  [self.depolyCollectionView reloadData];
  if (self.deployVM.dataSource.count % 10 > 0) {
    [self.depolyCollectionView.footer endRefreshingWithNoMoreData];
  }else{
    [self.depolyCollectionView.footer endRefreshing];
  }
  
  [self.depolyCollectionView.header endRefreshing];
  
  [SVProgressHUD dismiss];
}

#pragma mark - Private Methods

- (void)addObservers{
  @weakify(self)
  
  self.depolyCollectionView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
    @strongify(self)
    [self.deployVM first];
    [self.depolyCollectionView.footer resetNoMoreData];
  }];
  
  self.depolyCollectionView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
    @strongify(self)
    [self.deployVM next];
  }];

  
  
  [RACObserve(self.deployVM, dataSource) subscribeNext:^(id x) {
    @strongify(self)
    [self setUpStauts];
  }];
  
  [[[NSNotificationCenter defaultCenter] rac_addObserverForName:kSetGoodsDismiss object:nil] subscribeNext:^(id x) {
    @strongify(self)
    [self.deployVM first];
  }];
  
  [[[NSNotificationCenter defaultCenter] rac_addObserverForName:kSetBoatsDismiss object:nil] subscribeNext:^(id x) {
    @strongify(self)
    [self.deployVM first];
  }];
  
  [[[NSNotificationCenter defaultCenter] rac_addObserverForName:kRefreshBoatSuccess object:nil] subscribeNext:^(id x) {
    @strongify(self);
    [self.deployVM first];
  }];
  
  [[[NSNotificationCenter defaultCenter] rac_addObserverForName:kDeletAllSuccess object:nil] subscribeNext:^(id x) {
    [self.deployVM first];
    
  }];
  
}

- (void)toAddSome{
  
//  if (self.userType == 0) {
//    SLAddBoatViewController *vc = [SLAddBoatViewController new];
//      vc.hidesBottomBarWhenPushed = YES;
//    [self.navigationController pushViewController:vc animated:YES];
//  }else{
//    SLAddGoodsViewController *vc = [SLAddGoodsViewController new];
//      vc.hidesBottomBarWhenPushed = YES;
//    [self.navigationController pushViewController:vc animated:YES];
//  }
  
}

- (void)addConstrains{
  
  [self.shareBtn mas_makeConstraints:^(MASConstraintMaker *make) {
    make.centerY.equalTo(self.naviHeader.leftLabel);
    make.right.equalTo(self.naviHeader).offset(-15);
    make.size.mas_equalTo(CGSizeMake(50, 25));
  }];

    
    [self.historyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.shareBtn);
        make.right.equalTo(self.shareBtn).offset(-50);
        make.size.mas_equalTo(CGSizeMake(50, 25));
    }];
    
  if (self.userType == 1) {
    [self.depolyCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
      make.centerX.width.equalTo(self.view);
      make.top.equalTo(self.naviHeader.mas_bottom).offset(20);
      make.bottom.equalTo(self.mas_bottomLayoutGuideTop);
    }];
  }else{
    [self.view addSubview:self.scrollTextView];
    [self.view addSubview:self.warnImageView];
    [self.warnImageView mas_makeConstraints:^(MASConstraintMaker *make) {
      make.left.equalTo(self.view);
      make.centerY.equalTo(self.scrollTextView);
      make.size.mas_equalTo(CGSizeMake(25, 25));
    }];

    [self.scrollTextView startScroll];
    [self.depolyCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
      make.centerX.width.equalTo(self.view);
      make.top.equalTo(self.scrollTextView.mas_bottom).offset(20);
      make.bottom.equalTo(self.mas_bottomLayoutGuideTop);
    }];
  }
  
  
}

//返回标题文字
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView{
  if (!self.reach.isReachable) {
    return [[NSAttributedString alloc] initWithString:@"无网络连接, 请连接网络后刷新" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]}];
  }
  if(self.userType == 0){
    return [[NSAttributedString alloc] initWithString:@"赶快发布货源吧" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]}];
  }else{
    return [[NSAttributedString alloc] initWithString:@"暂无货源" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]}];
  }
    
}
//返回详情文字
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
{
    if (!self.reach.isReachable) {
        return [[NSAttributedString alloc] initWithString:@"无网络连接, 请连接网络后刷新" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]}];
    }
    return [[NSAttributedString alloc] initWithString:@"享受24小时智能推荐船舶服务" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]}];
}
- (UIImage *)buttonImageForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state
{
    return IMG(@"ic_arrow_down");
}


- (void)emptyDataSetDidTapView:(UIScrollView *)scrollView{
  DLog(@"点击了。。。。。。。。。");
  [self.depolyCollectionView.header beginRefreshing];
  [self.deployVM first];
}

#pragma mark - SLDeployBoatsCollectionViewCellDelegate

- (void)didTapedSetBtn:(SLDeployShip *)shipModel{
  SLSetBoatViewController *setBoatVC = [SLSetBoatViewController new];
  [setBoatVC showWithBid:shipModel.bid];
  setBoatVC.hidesBottomBarWhenPushed = YES;
  [self.navigationController pushViewController:setBoatVC animated:YES];

}

- (void)didTapedRecomBtn:(SLDeployShip *)shipModel{
  
  SLRecomendViewController *VC = [[SLRecomendViewController alloc] initWithBid:shipModel.bid];
  VC.hidesBottomBarWhenPushed = YES;
  [self.navigationController pushViewController:VC animated:YES];
}

- (void)didTapedRefreshBtn:(SLDeployShip *)shipModel{
  
  SLRefreshBoatViewController *boatRefreshVC = [[SLRefreshBoatViewController alloc] initWithState:shipModel];
  boatRefreshVC.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
  boatRefreshVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
  [self presentViewController:boatRefreshVC animated:YES completion:nil];
}


#pragma mark - SLDeployGoodsCollectionViewCellDelegate

- (void)cellRefreshBtnWasTaped:(SLDeployGood *)goodsModel{
  
  [self.deployVM refreshGoodsWith:0 gid:goodsModel.gid];
}

- (void)cellRecomendBtnWasTaped:(SLDeployGood *)goodsModel{
  SLRecomendViewController *VC = [[SLRecomendViewController alloc] initWithGid:goodsModel.gid];
  VC.hidesBottomBarWhenPushed = YES;
  [self.navigationController pushViewController:VC animated:YES];
}




#pragma mark - UICollectionViewDelegate, UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
  return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
  return self.deployVM.dataSource.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
  if ([[DEFAULTS objectForKey:@"userType"] isEqualToNumber:@1]) {
    SLDeployGoodsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"GoodsCell" forIndexPath:indexPath];
    cell.delegate = self;
    return cell;
  }else{
    SLDeployBoatsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"BoatsCell" forIndexPath:indexPath];
    cell.delegate = self;
    return cell;
  }
}


- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{
  if (self.userType == 1) {
    SLDeployGoodsCollectionViewCell *thisCell = (SLDeployGoodsCollectionViewCell *)cell;
    
    [thisCell configDepolyGoodsCellWith:self.deployVM.dataSource[indexPath.row]];
  }else{
    SLDeployBoatsCollectionViewCell *thisCell = (SLDeployBoatsCollectionViewCell *)cell;
    
    [thisCell configDeployBoatCellWithModel:self.deployVM.dataSource[indexPath.row]];
  }
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
  if (self.userType == 1) {
    SLSetGoodsViewController *setGoodsVC = [SLSetGoodsViewController new];
    SLDeployGood *model = self.deployVM.dataSource[indexPath.row];
    [setGoodsVC showWithGid:model.gid];
    setGoodsVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:setGoodsVC animated:YES];
  }
}



- (void)share{
  @weakify(self)
  
  SLShareManager *shareMg = [[SLShareManager alloc] init];
  [shareMg sharemydata:^(NSDictionary *shareData) {
    @strongify(self)
    [UMSocialData defaultData].extConfig.wechatSessionData.title = @"新码头";
    [UMSocialData defaultData].extConfig.wechatTimelineData.title =  @"新码头";
    [UMSocialData defaultData].extConfig.wechatSessionData.url = shareData[@"url"];
    [UMSocialData defaultData].extConfig.wechatTimelineData.url = shareData[@"url"];
    [UMSocialData defaultData].extConfig.qqData.title = @"新码头";
    [UMSocialData defaultData].extConfig.qqData.url = shareData[@"url"];
    [UMSocialData defaultData].extConfig.qzoneData.title = @"新码头";
    [UMSocialData defaultData].extConfig.qzoneData.url = shareData[@"url"];
    
    
    UIImage *shareImg;
    if (self.userType == 1) {
      shareImg = [UIImage imageNamed:@"sharecargo"];
    }else{
      shareImg = [UIImage imageNamed:@"shareship"];
    }
    
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:kUMengAppKey
                                      shareText: shareData[@"describe"]
                                     shareImage: shareImg
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToWechatSession,UMShareToWechatTimeline,UMShareToQQ,UMShareToQzone,nil]
                                       delegate:self];
  }];
}



#pragma mark - getter

- (UIButton *)shareBtn{
  if (!_shareBtn) {
    _shareBtn  = [UIButton buttonWithType:UIButtonTypeCustom];
    [_shareBtn setTitle:@"分享" forState:UIControlStateNormal];
    [_shareBtn setTitleColor:RGBCOLOR(253,207,0) forState:UIControlStateNormal];
    [_shareBtn addTarget:self action:@selector(share) forControlEvents:UIControlEventTouchUpInside];
  }
  return _shareBtn;
}

- (UIButton *)historyBtn{
  if (!_historyBtn) {
    _historyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_historyBtn setTitle:@"历史" forState: UIControlStateNormal];
    [_historyBtn setTitleColor:RGBCOLOR(253,207,0) forState:UIControlStateNormal];
    [_historyBtn addTarget:self action:@selector(toAddSome) forControlEvents:UIControlEventTouchUpInside];
  }
  return _historyBtn;
}

- (UICollectionView *)depolyCollectionView{
  if (!_depolyCollectionView) {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(SCREEN_WIDTH - 20, 220);
    _depolyCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    _depolyCollectionView.backgroundColor = [UIColor defeutBackgroudColor];
    [_depolyCollectionView registerNib:[UINib nibWithNibName:@"SLDeployBoatsCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"BoatsCell"];
    [_depolyCollectionView registerNib:[UINib nibWithNibName:@"SLDeployGoodsCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"GoodsCell"];
    _depolyCollectionView.delegate = self;
    _depolyCollectionView.dataSource = self;
    _depolyCollectionView.emptyDataSetSource = self;
    _depolyCollectionView.emptyDataSetDelegate = self;
  }
  return _depolyCollectionView;
}

- (SLMineViewModel *)mineModel{
  if (!_mineModel) {
    _mineModel = [SLMineViewModel shareInstance];
  }
  return _mineModel;
}

- (SLScrollerTextView *)scrollTextView{
  if (!_scrollTextView) {
    _scrollTextView = [[SLScrollerTextView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.naviHeader.frame), SCREEN_WIDTH, 0)];
    return _scrollTextView;
  }
  return _scrollTextView;
}
//- (UIImageView *)warnImageView{
//  if (!_warnImageView) {
//    _warnImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"prompt1"]];
//    _warnImageView.contentMode = UIViewContentModeScaleAspectFit;
//    _warnImageView.backgroundColor = SLYellowColor;
//  }
//  return _warnImageView;
//}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
